﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using System.Data.SqlClient;

using SIPO.Library;
using SIPO.Library.DomainObject.Administration.Catalog;
using SIPO.Library.Enum;
using SIPO.Library.Interfaces;

namespace SIPO.Library.DataAccess.Administration.Catalog
{
    public partial class JobTitleRepo : ISearchable<JobTitle>
    {
        public object SelectScalar(SQL.Function.Aggregate function, string column,string parameters)
        {
            object _result = null;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    StringBuilder sbQuery = new StringBuilder();
                    switch (function)
                    {
                        case SQL.Function.Aggregate.Max:
                            sbQuery.AppendFormat("SELECT MAX({0}) FROM master.JobTitle {1}", column,parameters);
                            break;
                        case SQL.Function.Aggregate.Min:
                            sbQuery.AppendFormat("SELECT MIN({0}) FROM master.JobTitle {1}", column, parameters);
                            break;
                        case SQL.Function.Aggregate.Distinct:
                            sbQuery.AppendFormat("SELECT DISTINCT({0}) FROM master.JobTitle {1}", column, parameters);
                            break;
                        case SQL.Function.Aggregate.Count:
                            sbQuery.AppendFormat("SELECT COUNT({0}) FROM master.JobTitle INNER JOIN master.Position ON Position.PositionID=JobTitle.PositionID INNER JOIN master.Department ON Position.DepartmentID = Department.DeptID {1}", column, parameters);
                            break;
                        case SQL.Function.Aggregate.Sum:
                            sbQuery.AppendFormat("SELECT SUM({0}) FROM master.JobTitle {1}", column, parameters);
                            break;
                        case SQL.Function.Aggregate.Avg:
                            sbQuery.AppendFormat("SELECT AVG({0}) FROM master.JobTitle {1}", column, parameters);
                            break;
                        default:
                            // do nothing 
                            break;
                    }

                    cmd.CommandText = sbQuery.ToString();
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        conn.Open();
                        _result = cmd.ExecuteScalar();
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return _result;
        }

        public List<JobTitle> GetList(int pageSize, int currentPage, string sortName, string sortOrder, string parameters)
        {
            List<JobTitle> tt = new List<JobTitle>();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    int startRow = ((currentPage - 1) * pageSize) + 1;
                    int endRow = (startRow + pageSize);

                    StringBuilder sbQuery = new StringBuilder();
                    sbQuery.AppendFormat(" WITH result_set AS ");
                    sbQuery.AppendFormat(" ( ");
                    sbQuery.AppendFormat("    SELECT ");
                    sbQuery.AppendFormat("      ROW_NUMBER() OVER (ORDER BY {0} {1}) AS [row_number], ", sortName, sortOrder);
                    sbQuery.AppendFormat("      JobTitle.JobtitleID, JobTitle.RowStatus, JobTitle.PositionID, JobTitle.MinEducation, JobTitle.Major, JobTitle.MinExperience, JobTitle.WorkingExperience, JobTitle.Specification, JobTitle.FunctionalCompetency, JobTitle.Challenge, JobTitle.Authority, JobTitle.ImageOrganitation, JobTitle.CreatedDate, JobTitle.CreatedBy, JobTitle.UpdatedDate, JobTitle.UpdatedBy,Position.PositionName,Department.DepartmentDesc ");
                    sbQuery.AppendFormat("    FROM ");
                    sbQuery.AppendFormat("      master.JobTitle INNER JOIN master.Position ON Position.PositionID=JobTitle.PositionID INNER JOIN master.Department ON Position.DepartmentID = Department.DeptID   ");
                    sbQuery.AppendFormat("     {0} ",parameters);
                    sbQuery.AppendFormat(" ) ");
                    sbQuery.AppendFormat(" SELECT * FROM result_set WHERE [row_number] BETWEEN {0} AND {1} ", startRow, endRow);

                    cmd.CommandText = sbQuery.ToString();
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {
                                JobTitle t = new JobTitle(true);
                                t.JobtitleID = dr[JobTitle.Fields.JobtitleID] == DBNull.Value ? 0 : int.Parse(dr[JobTitle.Fields.JobtitleID].ToString());
                                t.RowStatus = dr[JobTitle.Fields.RowStatus] == DBNull.Value ? (bool?)null : bool.Parse(dr[JobTitle.Fields.RowStatus].ToString());
                                t.PositionID = dr[JobTitle.Fields.PositionID] == DBNull.Value ? (int?)null : int.Parse(dr[JobTitle.Fields.PositionID].ToString());
                                t.MinEducation = dr[JobTitle.Fields.MinEducation] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.MinEducation].ToString();
                                t.Major = dr[JobTitle.Fields.Major] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.Major].ToString();
                                t.MinExperience = dr[JobTitle.Fields.MinExperience] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.MinExperience].ToString();
                                t.WorkingExperience = dr[JobTitle.Fields.WorkingExperience] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.WorkingExperience].ToString();
                                t.Specification = dr[JobTitle.Fields.Specification] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.Specification].ToString();
                                t.FunctionalCompetency = dr[JobTitle.Fields.FunctionalCompetency] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.FunctionalCompetency].ToString();
                                t.Challenge = dr[JobTitle.Fields.Challenge] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.Challenge].ToString();
                                t.Authority = dr[JobTitle.Fields.Authority] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.Authority].ToString();
                                t.ImageOrganitation = dr[JobTitle.Fields.ImageOrganitation] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.ImageOrganitation].ToString();
                                t.CreatedDate = dr[JobTitle.Fields.CreatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[JobTitle.Fields.CreatedDate].ToString());
                                t.CreatedBy = dr[JobTitle.Fields.CreatedBy] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.CreatedBy].ToString();
                                t.UpdatedDate = dr[JobTitle.Fields.UpdatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[JobTitle.Fields.UpdatedDate].ToString());
                                t.UpdatedBy = dr[JobTitle.Fields.UpdatedBy] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.UpdatedBy].ToString();

                                
                                t.Position = new Position(true);
                                t.Position.PositionName = dr[Position.Fields.PositionName] == DBNull.Value ? string.Empty : dr[Position.Fields.PositionName].ToString();
                                t.Position.Department.DepartmentDesc = dr[Department.Fields.DepartmentDesc] == DBNull.Value ? string.Empty : dr[Department.Fields.DepartmentDesc].ToString();

                                tt.Add(t);
                                t.Dispose();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return tt;
        }

        public JobTitle GetByPositionId(int positionID)
        {
            JobTitle t = null;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "SELECT JobtitleID, RowStatus, PositionID, MinEducation, Major, MinExperience, WorkingExperience, Specification, FunctionalCompetency, Challenge, Authority, ImageOrganitation, CreatedDate, CreatedBy, UpdatedDate, UpdatedBy FROM master.JobTitle WHERE PositionID = @PositionID";
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add("@PositionID", SqlDbType.Int).Value = positionID;
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {
                                t = new JobTitle();
                                t.JobtitleID = dr[JobTitle.Fields.JobtitleID] == DBNull.Value ? 0 : int.Parse(dr[JobTitle.Fields.JobtitleID].ToString());
                                t.RowStatus = dr[JobTitle.Fields.RowStatus] == DBNull.Value ? (bool?)null : bool.Parse(dr[JobTitle.Fields.RowStatus].ToString());
                                t.PositionID = dr[JobTitle.Fields.PositionID] == DBNull.Value ? (int?)null : int.Parse(dr[JobTitle.Fields.PositionID].ToString());
                                t.MinEducation = dr[JobTitle.Fields.MinEducation] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.MinEducation].ToString();
                                t.Major = dr[JobTitle.Fields.Major] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.Major].ToString();
                                t.MinExperience = dr[JobTitle.Fields.MinExperience] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.MinExperience].ToString();
                                t.WorkingExperience = dr[JobTitle.Fields.WorkingExperience] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.WorkingExperience].ToString();
                                t.Specification = dr[JobTitle.Fields.Specification] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.Specification].ToString();
                                t.FunctionalCompetency = dr[JobTitle.Fields.FunctionalCompetency] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.FunctionalCompetency].ToString();
                                t.Challenge = dr[JobTitle.Fields.Challenge] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.Challenge].ToString();
                                t.Authority = dr[JobTitle.Fields.Authority] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.Authority].ToString();
                                t.ImageOrganitation = dr[JobTitle.Fields.ImageOrganitation] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.ImageOrganitation].ToString();
                                t.CreatedDate = dr[JobTitle.Fields.CreatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[JobTitle.Fields.CreatedDate].ToString());
                                t.CreatedBy = dr[JobTitle.Fields.CreatedBy] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.CreatedBy].ToString();
                                t.UpdatedDate = dr[JobTitle.Fields.UpdatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[JobTitle.Fields.UpdatedDate].ToString());
                                t.UpdatedBy = dr[JobTitle.Fields.UpdatedBy] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.UpdatedBy].ToString();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return t;
        }

        public List<JobTitle> GetListByPositionID(int positionID)
        {
            List<JobTitle> tt = new List<JobTitle>();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "SELECT JobtitleID, RowStatus, PositionID, MinEducation, Major, MinExperience, WorkingExperience, Specification, FunctionalCompetency, Challenge, Authority, ImageOrganitation, CreatedDate, CreatedBy, UpdatedDate, UpdatedBy FROM master.JobTitle WHERE PositionID = @PositionID";
                    cmd.Parameters.Add("@PositionID", SqlDbType.Int).Value = positionID;
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {
                                JobTitle t = new JobTitle();
                                t.JobtitleID = dr[JobTitle.Fields.JobtitleID] == DBNull.Value ? 0 : int.Parse(dr[JobTitle.Fields.JobtitleID].ToString());
                                t.RowStatus = dr[JobTitle.Fields.RowStatus] == DBNull.Value ? (bool?)null : bool.Parse(dr[JobTitle.Fields.RowStatus].ToString());
                                t.PositionID = dr[JobTitle.Fields.PositionID] == DBNull.Value ? (int?)null : int.Parse(dr[JobTitle.Fields.PositionID].ToString());
                                t.MinEducation = dr[JobTitle.Fields.MinEducation] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.MinEducation].ToString();
                                t.Major = dr[JobTitle.Fields.Major] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.Major].ToString();
                                t.MinExperience = dr[JobTitle.Fields.MinExperience] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.MinExperience].ToString();
                                t.WorkingExperience = dr[JobTitle.Fields.WorkingExperience] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.WorkingExperience].ToString();
                                t.Specification = dr[JobTitle.Fields.Specification] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.Specification].ToString();
                                t.FunctionalCompetency = dr[JobTitle.Fields.FunctionalCompetency] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.FunctionalCompetency].ToString();
                                t.Challenge = dr[JobTitle.Fields.Challenge] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.Challenge].ToString();
                                t.Authority = dr[JobTitle.Fields.Authority] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.Authority].ToString();
                                t.ImageOrganitation = dr[JobTitle.Fields.ImageOrganitation] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.ImageOrganitation].ToString();
                                t.CreatedDate = dr[JobTitle.Fields.CreatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[JobTitle.Fields.CreatedDate].ToString());
                                t.CreatedBy = dr[JobTitle.Fields.CreatedBy] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.CreatedBy].ToString();
                                t.UpdatedDate = dr[JobTitle.Fields.UpdatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[JobTitle.Fields.UpdatedDate].ToString());
                                t.UpdatedBy = dr[JobTitle.Fields.UpdatedBy] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.UpdatedBy].ToString();
                                tt.Add(t);
                                t.Dispose();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return tt;
        }

        public List<JobTitle> GetListByPositionID(int positionID,int programID)
        {
            List<JobTitle> tt = new List<JobTitle>();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "SELECT JobtitleID, RowStatus, PositionID, MinEducation, Major, MinExperience, WorkingExperience, Specification, FunctionalCompetency, Challenge, Authority, ImageOrganitation, CreatedDate, CreatedBy, UpdatedDate, UpdatedBy FROM master.JobTitle WHERE PositionID = @PositionID AND ProgramID=@ProgramID";
                    cmd.Parameters.Add("@PositionID", SqlDbType.Int).Value = positionID;
                    cmd.Parameters.Add("@ProgramID", SqlDbType.Int).Value = programID;
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {
                                JobTitle t = new JobTitle();
                                t.JobtitleID = dr[JobTitle.Fields.JobtitleID] == DBNull.Value ? 0 : int.Parse(dr[JobTitle.Fields.JobtitleID].ToString());
                                t.RowStatus = dr[JobTitle.Fields.RowStatus] == DBNull.Value ? (bool?)null : bool.Parse(dr[JobTitle.Fields.RowStatus].ToString());
                                t.PositionID = dr[JobTitle.Fields.PositionID] == DBNull.Value ? (int?)null : int.Parse(dr[JobTitle.Fields.PositionID].ToString());
                                t.MinEducation = dr[JobTitle.Fields.MinEducation] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.MinEducation].ToString();
                                t.Major = dr[JobTitle.Fields.Major] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.Major].ToString();
                                t.MinExperience = dr[JobTitle.Fields.MinExperience] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.MinExperience].ToString();
                                t.WorkingExperience = dr[JobTitle.Fields.WorkingExperience] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.WorkingExperience].ToString();
                                t.Specification = dr[JobTitle.Fields.Specification] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.Specification].ToString();
                                t.FunctionalCompetency = dr[JobTitle.Fields.FunctionalCompetency] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.FunctionalCompetency].ToString();
                                t.Challenge = dr[JobTitle.Fields.Challenge] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.Challenge].ToString();
                                t.Authority = dr[JobTitle.Fields.Authority] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.Authority].ToString();
                                t.ImageOrganitation = dr[JobTitle.Fields.ImageOrganitation] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.ImageOrganitation].ToString();
                                t.CreatedDate = dr[JobTitle.Fields.CreatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[JobTitle.Fields.CreatedDate].ToString());
                                t.CreatedBy = dr[JobTitle.Fields.CreatedBy] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.CreatedBy].ToString();
                                t.UpdatedDate = dr[JobTitle.Fields.UpdatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[JobTitle.Fields.UpdatedDate].ToString());
                                t.UpdatedBy = dr[JobTitle.Fields.UpdatedBy] == DBNull.Value ? string.Empty : dr[JobTitle.Fields.UpdatedBy].ToString();
                                tt.Add(t);
                                t.Dispose();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return tt;
        }

        public DataTable GetDataTableReport(string param)
        {
            DataTable dt = new DataTable();

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {

                    StringBuilder sbQuery = new StringBuilder();

                    sbQuery.AppendLine("SELECT C.DepartmentDesc Departemen");
                    sbQuery.AppendLine(",B.PositionName Jabatan");
                    sbQuery.AppendLine(",A.MinEducation");
                    sbQuery.AppendLine(",A.Major");
                    sbQuery.AppendLine(",A.MinExperience");
                    sbQuery.AppendLine(",A.WorkingExperience");
                    sbQuery.AppendLine(",A.Specification");
                    sbQuery.AppendLine(",A.FunctionalCompetency");
                    sbQuery.AppendLine(",A.Challenge");
                    sbQuery.AppendLine(",A.Authority");
                    sbQuery.AppendLine("FROM  master.JobTitle A ");
                    sbQuery.AppendLine("INNER JOIN master.Position B ON A.PositionID = B.PositionID");
                    sbQuery.AppendLine("INNER JOIN master.Department C ON B.DepartmentID = C.DeptID");
                    sbQuery.AppendLine(param);

                    //if (param.Trim().Length > 0)
                    //    sbQuery.AppendFormat("WHERE B.DepartmentID IN {0}",param);

                    cmd.CommandText = sbQuery.ToString();
                    //if (param.Trim().Length > 0)
                    //    cmd.Parameters.Add("@DepartmentID", SqlDbType.Int).Value = param;

                    SqlDataAdapter da = new SqlDataAdapter();
                    da.SelectCommand = cmd;

                    try
                    {
                        conn.Open();
                        da.Fill(dt);
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }

                }
            }

            return dt;

        }
    }
}
